import { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';

interface HorizontalBarProps {
  data: Array<{
    type: string;
    value: number;
  }>;
  draw?: boolean;
  height?: number;
  // 添加颜色配置属性
  colors?: string[];
}

const EHorizontalBar = (props: HorizontalBarProps) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const { data, draw, height = 300, colors } = props;

  useEffect(() => {
    if (!data.length || !draw || !chartRef.current) return;

    // 初始化图表
    const chart = echarts.init(chartRef.current);

    // 准备数据
    const types = data.map(item => item.type);
    const values = data.map(item => item.value);

    // 配置项
    const options: EChartsOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params: any) => {
          const param = params[0];
          return `${param.name}<br/>响应时长（分钟）：${param.value}`;
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}'
        }
      },
      yAxis: {
        type: 'category',
        data: types,
        axisLine: {
          show: true
        },
        axisTick: {
          show: true
        }
      },
      series: [
        {
          type: 'bar',
          data: values,
          barWidth: 20,
          itemStyle: {
            color: function(params: any) {
              if (colors) {
                return colors[params.dataIndex % colors.length];
              }
              const defaultColors = [
                '#5B8FF9', '#5AD8A6', '#5D7092', '#F6BD16', '#E8684A', 
                '#6DC8EC', '#9270CA', '#FF9D4D', '#269A99', '#FF99C3'
              ];
              return defaultColors[params.dataIndex % defaultColors.length];
            }
          }
        }
      ]
    };

    // 设置配置项
    chart.setOption(options);

    // 响应式处理
    const handleResize = () => {
      chart.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      chart.dispose();
      window.removeEventListener('resize', handleResize);
    };
  }, [data, draw]);

  return (
    <div
      ref={chartRef}
      style={{ width: '100%', height: height || 300 }}
    />
  );
};

export default EHorizontalBar;